"use client";

import { useEffect, useState } from "react";
import { Modal, Form, Input, DatePicker, Select, Button } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { type Task } from "@prisma/client";
import { api } from "~/trpc/react";
import dayjs from "dayjs";

interface TaskFormValues {
  title: string;
  description?: string;
  content?: string;
  dueDate?: dayjs.Dayjs;
  status: "NOT_STARTED" | "IN_PROGRESS" | "COMPLETED";
  priority: "LOW" | "MEDIUM" | "HIGH";
  steps?: {
    title: string;
    description?: string;
    orderIndex: number;
  }[];
}

interface TaskFormProps {
  courseId: string;
  open: boolean;
  initialValues?: Task & {
    steps?: {
      id: string;
      title: string;
      description: string | null;
      orderIndex: number;
    }[];
  };
  onCancel: () => void;
  onSuccess: () => void;
}

export function TaskForm({ courseId, open, initialValues, onCancel, onSuccess }: TaskFormProps) {
  const [form] = Form.useForm<TaskFormValues>();
  const [mounted, setMounted] = useState(false);

  const createMutation = api.tasks.create.useMutation({
    onSuccess: () => {
      form.resetFields();
      onSuccess();
    },
  });

  const updateMutation = api.tasks.update.useMutation({
    onSuccess: () => {
      form.resetFields();
      onSuccess();
    },
  });

  // 修改 mounted 状态控制
  useEffect(() => {
    if (open) {
      setMounted(true);
    }
  }, [open]);

  // 处理表单初始值
  useEffect(() => {
    if (open && initialValues) {
      form.setFieldsValue({
        ...initialValues,
        dueDate: initialValues.dueDate ? dayjs(initialValues.dueDate) : undefined,
        steps: initialValues.steps?.map((step, index) => ({
          ...step,
          orderIndex: index,
        })) || [],
      });
    }
  }, [open, initialValues, form]);

  const handleSubmit = async (values: TaskFormValues) => {
    try {
      // 处理步骤顺序和日期转换
      const formData = {
        ...values,
        dueDate: values.dueDate ? values.dueDate.toDate() : undefined,
        steps: values.steps?.map((step, index) => ({
          title: step.title,
          description: step.description,
          orderIndex: index
        }))
      };

      if (initialValues) {
        await updateMutation.mutateAsync({
          taskId: initialValues.id,
          ...formData,
        });
      } else {
        await createMutation.mutateAsync({
          courseId,
          ...formData,
        });
      }
      onSuccess();
    } catch (error) {
      console.error("提交任务表单时出错:", error);
    }
  };

  // 处理Modal关闭后的清理
  const handleAfterClose = () => {
    form.resetFields();
    if (!open) {
      setMounted(false);
    }
  };

  // 修改渲染逻辑
  if (!mounted && !open) {
    return null;
  }

  return (
    <Modal
      title={initialValues ? "编辑任务" : "新建任务"}
      open={open}
      onCancel={onCancel}
      afterClose={handleAfterClose}
      onOk={() => form.submit()}
      confirmLoading={createMutation.isLoading || updateMutation.isLoading}
      width={720}
      destroyOnClose
    >
      {mounted && (
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            status: "NOT_STARTED",
            priority: "MEDIUM",
            steps: [],
          }}
        >
          <Form.Item
            name="title"
            label="任务标题"
            rules={[{ required: true, message: "请输入任务标题" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item name="description" label="任务描述">
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item name="dueDate" label="截止日期">
            <DatePicker 
              style={{ width: "100%" }} 
              showTime={false}
              format="YYYY-MM-DD"
            />
          </Form.Item>

          <Form.Item name="status" label="状态">
            <Select>
              <Select.Option value="NOT_STARTED">未开始</Select.Option>
              <Select.Option value="IN_PROGRESS">进行中</Select.Option>
              <Select.Option value="COMPLETED">已完成</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="priority" label="优先级">
            <Select>
              <Select.Option value="LOW">低</Select.Option>
              <Select.Option value="MEDIUM">中</Select.Option>
              <Select.Option value="HIGH">高</Select.Option>
            </Select>
          </Form.Item>

          <Form.List name="steps">
            {(fields, { add, remove }) => (
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <h3 className="text-lg font-medium">步骤</h3>
                  <Button type="link" onClick={() => add()} icon={<PlusOutlined />}>
                    添加步骤
                  </Button>
                </div>
                {fields.map((field, index) => {
                  const { key, ...restField } = field;
                  return (
                    <div key={key} className="border rounded-md p-4 space-y-2">
                      <div className="flex justify-between items-center">
                        <h4 className="text-base font-medium">步骤 {index + 1}</h4>
                        <Button
                          type="text"
                          danger
                          icon={<DeleteOutlined />}
                          onClick={() => remove(field.name)}
                        />
                      </div>
                      <Form.Item
                        {...restField}
                        name={[field.name, "title"]}
                        rules={[{ required: true, message: "请输入步骤标题" }]}
                      >
                        <Input placeholder="步骤标题" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[field.name, "description"]}
                      >
                        <Input.TextArea
                          placeholder="步骤描述（可选）"
                          rows={2}
                        />
                      </Form.Item>
                    </div>
                  );
                })}
              </div>
            )}
          </Form.List>

          <Form.Item name="content" label="任务内容">
            <Input.TextArea rows={6} />
          </Form.Item>
        </Form>
      )}
    </Modal>
  );
} 